import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import { nanoid } from 'nanoid'


export default class Header extends Component {
    state = { title: '' }
    addItem = () => {
        if (!this.state.title) {
            return alert("添加内容不能为空！");
        }
        PubSub.publish("addItem", {
            id: nanoid(4),
            title: this.state.title,
            done: false
        })
        this.setState({ title: "" })
    }
    changeTitle = (e) => {
        var title = e.currentTarget.value.trim();
        if (!title) {
            return false;
        }
        this.setState({ title })
    }
    keySubmit = (e) => {
        if (e.keyCode == 13) {
            this.addItem();
        }
    }
    render() {
        return (
            <div className='header-wrapper' onKeyUp={this.keySubmit}>
                <input onChange={this.changeTitle} value={this.state.title} />
                <button className='btn' onClick={this.addItem}>添加</button>
            </div>
        )
    }
}
